package LeetCode.exercise;

import java.util.*;

public class LC207 {
    public static void main(String[] args) {
        LC207 main = new LC207();
        boolean b = main.canFinish(5, new int[][]{{1, 4}, {2, 4}, {3, 1}, {3, 2}});
        System.out.println(b);
    }
    public boolean canFinish(int numCourses, int[][] prerequisites) {
        int[] in = new int[numCourses];
        Map<Integer, List<Integer>> edges = new HashMap<>();
        for(int i = 0; i < prerequisites.length; i++){
            int a = prerequisites[i][0], b = prerequisites[i][1];
            // b -> a
            if(!edges.containsKey(b)){
                edges.put(b, new ArrayList<>());
            }
            edges.get(b).add(a);
            in[a]++;
        }
        Queue<Integer> q = new LinkedList<>();
        for(int i = 0; i < numCourses; i++){
            if(in[i] == 0){
                q.offer(i);
            }
        }
        while(!q.isEmpty()){
            int tmp = q.poll();
            for(Integer cur : edges.getOrDefault(tmp, new ArrayList<>())){
                if(--in[cur] == 0){
                    q.offer(cur);
                }
            }
            edges.remove(tmp);
        }
        return edges.isEmpty();
    }
}
